<template>
  <div class="wrapper">
    <el-card>
      <div class="rowDiv">
        <div class="row-left">
          <div class="row-item">
            <span class="demonstration">时间范围&nbsp;</span>
            <Date @dateFun="dateFun"></Date>
          </div>
          <div class="row-item">
            仓库名称&nbsp;<el-select
              v-model="state.warehouse_id"
              placeholder="选择仓库名称"
              clearable
              class="select"
              @change="changeSelectFun"
            >
              <template
                v-for="(item, index) in state.warehouseArr"
                :key="index"
              >
                <el-option
                  :value="item.warehouse_id"
                  :label="item.name"
                ></el-option>
              </template>
            </el-select>
          </div>
          <div class="row-item">
            库存类型&nbsp;<el-select
              v-model="state.type"
              placeholder="选择库存类型"
              class="select"
              clearable
              @change="changeSelectFun"
            >
              <template v-for="(item, index) in state.wareTypeArr" :key="index">
                <el-option :value="item.id" :label="item.name"></el-option>
              </template>
            </el-select>
          </div>
          <div class="row-item">
            库存来源:
            <el-select
              v-model="state.source"
              placeholder="选择库存来源"
              class="select"
              clearable
              @change="changeSelectFun"
            >
              <template v-for="(item, index) in state.sourceArr" :key="index">
                <el-option :value="item.id" :label="item.name"></el-option>
              </template>
            </el-select>
          </div>
        </div>
        <div class="row-right">
          <el-button type="primary" @click="new_set_ware">手动入库</el-button>
        </div>
      </div>
      <!--<el-table-->
      <!--@selection-change="handleSelectionChange"-->
      <!--ref="multipleTable" :data="state.tableData" style="width: 100%; margin-top: 20px">-->
      <!--<el-table-column type="selection"> </el-table-column>-->
      <el-table :data="state.tableData" style="width: 100%; margin-top: 20px">
        <el-table-column fixed label="编号（ID）" v-slot="scope">{{
          scope.$index + 1
        }}</el-table-column>
        <el-table-column
          fixed
          prop="good_warehouse"
          label="仓库"
        ></el-table-column>
        <el-table-column prop="good_name" label="商品名称"></el-table-column>
        <el-table-column prop="" label="批次号">？？？</el-table-column>
        <el-table-column prop="good_count" label="数量（袋）"></el-table-column>
        <el-table-column
          prop="goods_cartons"
          label="数量（箱）"
        ></el-table-column>
        <el-table-column prop="left_stock" label="库存（袋）"></el-table-column>
        <el-table-column
          prop="inventory_cartons"
          label="库存（箱）"
        ></el-table-column>
        <el-table-column prop="good_io_type" label="库存类型"></el-table-column>
        <el-table-column prop="source" label="库存来源"></el-table-column>
        <el-table-column prop="note" label="备注"></el-table-column>
        <el-table-column label="操作" v-slot="scope">
          <div>{{ scope.row.operator }}</div>
          <div>{{ scope.row.operate_time }}</div>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" class="marTop">
        <!--<el-col :span="12">-->
        <!--<el-checkbox-->
        <!--@change="checkAll"-->
        <!--v-model="state.pageChecked"-->
        <!--label="本页全选"-->
        <!--name="type"-->
        <!--&gt;</el-checkbox><el-button @click="unbind_all_Btn">导出</el-button>-->
        <!--</el-col>-->
        <el-col :span="12">
          <Page
            v-if="state.totalPage"
            :totalPage="state.totalPage"
            @changePage="changePage"
          ></Page>
        </el-col>
      </el-row>
      <!-- 新建仓库 -->
      <el-dialog
        title="编辑"
        v-model="state.new_dialogVisible"
        width="40%"
        center
      >
        <span>
          <el-form
            :model="state.set_form"
            :rules="state.rules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item type="flex" class="el-form-item-flex">
              <el-select
                v-model="state.set_form.warehouse_id"
                placeholder="选择仓库名称"
                class="select"
              >
                <template
                  v-for="(item, index) in state.warehouseArr"
                  :key="index"
                >
                  <el-option
                    :value="item.warehouse_id"
                    :label="item.name"
                  ></el-option>
                </template>
              </el-select>
              <el-input
                v-model="state.set_form.keyword"
                clearable
                class="input-keyword"
                placeholder="请输入商品名称、条形码"
              ></el-input>
              <el-button type="primary" @click="getGoodslist">搜索</el-button>
            </el-form-item>
            <el-form-item label="名称" prop="goods_name">
              <el-select
                v-model="state.set_form.goods_id"
                placeholder="选择名称"
                class="select_w100"
                @change="getCarturnFun"
              >
                <template v-for="(item, index) in state.goodsArr" :key="index">
                  <el-option
                    :value="item.good_id"
                    :label="item.good_name"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="count">
              <el-input
                v-model="state.set_form.count"
                type="number"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-select
                v-model="state.set_form.unit"
                placeholder="选择单位"
                class="select_w100"
              >
                <el-option value="0" label="袋"></el-option>
                <el-option value="1" label="箱"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="金额" prop="price">
              <el-input
                v-model="state.set_form.price"
                type="number"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="note" clearable>
              <el-input v-model="state.set_form.note"></el-input>
            </el-form-item>

            <el-form-item label="库存成本" class="color-red">
              {{ state.good_pur_price }}元/千克
            </el-form-item>
            <el-form-item label="入库成本" class="color-red">
              {{ ware_cost_total }}元/千克
            </el-form-item>
          </el-form>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close_dialog">取 消</el-button>
            <el-button type="primary" @click="submit_create">提 交</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import searchDiv from "@/components/Search.vue";
import Page from "@/components/Pagination.vue";
import Date from "@/components/Datepicker.vue";
import { ElNotification } from "element-plus";

export default {
    name:"inventory_record",
  components: { searchDiv, Page, Date },
  props: {},
  setup() {
    let multipleTable = ref("null");
    let form = ref(null);
    const { ctx } = getCurrentInstance();
    const router = useRouter();
    // 入库成本计算
    const ware_cost_total = computed(() => {
      var count = state.set_form.count == "" ? 1 : Number(state.set_form.count);
      var price = state.set_form.price == "" ? 0 : Number(state.set_form.price);
      var total = 0;
      if (state.set_form.unit == 0) {
        //袋
        total = (price / count).toFixed(2);
      } else {
        //箱
        total = (price / count / Number(state.carturnVal)).toFixed(2);
      }
      return total;
    });

    let state = reactive({
      totalPage: "",
      time: "",
      // pageChecked: false,
      multipleSelection: [],
      tableData: [],
      warehouseArr: [], //仓库数据
      warehouse_id: "", //仓库名称
      start_time: "",
      end_time: "",
      keyword: "",
      type: 0, //库存类型
      source: 0, //库存来源
      page: 0,
      sourceArr: [
        //来源
        {
          id: 0,
          name: "全部",
        },
        {
          id: 10,
          name: "手动",
        },
        {
          id: 20,
          name: "订单",
        },
        {
          id: 30,
          name: "报损",
        },
        {
          id: 40,
          name: "调拨",
        },
        {
          id: 50,
          name: "采购",
        },
      ],
      wareTypeArr: [
        //库存类型
        {
          id: 0,
          name: "全部",
        },
        {
          id: 10,
          name: "入库",
        },
        {
          id: 20,
          name: "出库",
        },
      ],
      new_dialogVisible: false,
      set_form: {
        warehouse_id: "",
        keyword: "",
        goods_id: "",
        count: 1,
        unit: "0",
        price: "",
        note: "",
      },
      rules: {
        count: [{ required: true, message: "请输入数量", trigger: "blur" }],
        price: [{ required: true, message: "请输入金额", trigger: "blur" }],
      },
      goodsArr: [], //商品数据
      good_pur_price: 0, //库存成本
      carturnVal: "", //计算入库成本的箱规
    });
    onMounted(() => {
      getWarehouseList();
      getOrderlist();
    });

    function dateFun(e) {
      state.start_time = e.begin_date;
      state.end_time = e.end_date;
      getOrderlist();
    }
    // 打开新建弹窗
    function new_set_ware() {
      state.new_dialogVisible = true;
      state.set_form.warehouse_id = state.warehouseArr[0].warehouse_id;
    }

    // 关闭弹窗--并清除表单信息
    function close_dialog() {
      state.new_dialogVisible = false;
    }

    //获取箱规
    function getCarturnFun(good_id) {
      var item = state.goodsArr.filter((obj) => good_id == obj.good_id);
      state.carturnVal = item[0].good_carton;
      state.good_pur_price = item[0].good_pur_price;
      console.log(Number(state.carturnVal));
    }

    //提交
    function submit_create() {
      let item = state.set_form;
      let data = {
        warehouse_id: item.warehouse_id,
        good_id: item.goods_id,
        count: item.count,
        total_price: ware_cost_total.value,
        note: item.note,
        is_boxful: 0,
      };
       console.log(data);
      form.value.validate((valid) => {
        if (valid) {
          ctx.$http
            .post("/tanxiaji/stock_goods_in/", data)
            .then((res) => {
              if (res.errno == 0) {
                ElNotification.success(res.errmsg);
                close_dialog();
                getOrderlist();
              } else {
                ElNotification.error(res.errmsg);
              }
            })
            .catch((err) => {
              ElNotification.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }

    //获取列表数据
    function getOrderlist() {
      ctx.$http
        .get("/tanxiaji/stock_record_list/", {
          start_time: state.start_time,
          end_time: state.end_time,
          warehouse_id: state.warehouse_id,
          keyword: state.keyword,
          type: state.type,
          source: state.source,
          page: state.page,
        })
        .then((res) => {
          if (res.errno == 0) {
            var list = res.data;
            state.tableData = list.stock_list;
            state.totalPage = list.total_page;
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    //选择select
    function changeSelectFun() {
      getOrderlist();
    }

    //获取商品数据
    function getGoodslist() {
      ctx.$http
        .get("/tanxiaji/stock_goods_in_search/", {
          keyword: state.set_form.keyword,
          warehouse_id: state.set_form.warehouse_id,
        })
        .then((res) => {
          if (res.errno == 0) {
            var list = res.data;
            state.goodsArr = list;
            state.set_form.goods_id = list[0].good_id;
            state.good_pur_price = list[0].good_pur_price;
            state.carturnVal = list[0].good_carton;
            state.set_form.price = list[0].good_pur_price;
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    //获取仓库数据
    function getWarehouseList() {
      ctx.$http
        .get("/tanxiaji/erp/depot/ajax/search/", {
          type: 1,
          need_agent: 1,
        })
        .then((res) => {
          if (res.errno == 0) {
            var list = res.data;
            state.warehouseArr = list;
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    function searchClick(searchCon) {
      console.log("子组件", searchCon);
    }

    //表格选择
    function handleSelectionChange(val) {
      state.multipleSelection = val;
    }

    //全选
    function checkAll() {
      state.multipleSelection = [];
      if (state.pageChecked) {
        multipleTable.value.toggleAllSelection();
        state.multipleSelection.push(state.tableData.filter((v) => v.date));
      } else {
        multipleTable.value.clearSelection();
        state.multipleSelection = [];
      }
    }

    //页码
    function changePage() {
      console.log("页码");
    }

    // 创建仓库
    return {
      form,
      multipleTable,
      handleSelectionChange,
      searchClick,
      state,
      checkAll,
      changePage,
      changeSelectFun,
      new_set_ware,
      getGoodslist,
      close_dialog,
      submit_create,
      getCarturnFun,
      ware_cost_total,
      dateFun,
    };
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
  .el-card {
    height: 100%;
    .cart-title::before {
      content: " ";
      width: 4px;
      height: 20px;
      background: #1890ff;
      background: #1890ff;
      display: inline-block;
      vertical-align: middle;
      margin-right: 5px;
    }
    .rowDiv {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      .row-left {
        display: flex;
        width: 70%;
        justify-content: space-between;
        .row-item {
          display: flex;
          align-items: center;
          white-space: nowrap;
        }
      }
      .row-right {
        width: 15%;
        display: flex;
        justify-content: flex-end;
      }
    }
    .el-table /deep/ th {
      background-color: #eaeaea;
      text-align: center;
    }
    .el-table /deep/ td {
      text-align: center;
    }
    .el-select {
      width: 100%;
    }
    .marRight {
      margin-right: 20px;
    }
    .marTop {
      margin-top: 10px;
    }
    .select {
      max-width: 150px;
    }
  }
  .el-form-item-flex {
    width: 100%;
    display: flex;
    .input-keyword {
      width: 48%;
    }
    .input_w50 {
      width: 48%;
    }
    .select_w100 {
      width: 100%;
    }
  }
  .color-red {
    color: red;
  }
}
</style>